﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace EMall.Middlewares
{
    public class RequestLoggingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;
        public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger)
        {
            ArgumentNullException.ThrowIfNull(next);
            ArgumentNullException.ThrowIfNull(logger);
            _next = next;
            _logger = logger;
        }
        public async Task Invoke(HttpContext httpContext)
        {
            var startTimestamp = TimeProvider.System.GetTimestamp();
            await _next(httpContext);
            var totalMilliseconds = (int)TimeProvider.System.GetElapsedTime(startTimestamp).TotalMilliseconds;
            _logger.LogInformation($"[{httpContext.Request.Host}] {httpContext.Request.Protocol} {httpContext.Request.Method} {httpContext.Request.Path.ToString()} [{httpContext.Response.StatusCode}] {totalMilliseconds} ms");
        }
    }
    public static class RequestLoggingAppBuilderExtensions
    {
        public static IApplicationBuilder UseRequestLogging(this IApplicationBuilder app)
        {
            ArgumentNullException.ThrowIfNull(app);
            //app.UseSerilogRequestLogging();
            return app.UseMiddleware<RequestLoggingMiddleware>();
        }
    }
}
